﻿using HslCommunication.ModBus;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Input;
using aichat.Entities;
using aichat.Services;
using System.Windows;

namespace aichat
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly ICabinetInfoService _cabinetInfoService;
        private readonly IUserService _userService;
        private readonly IChatService _chatService;
        private readonly IPaymentService _paymentService;
        private CancellationTokenSource cts = new CancellationTokenSource();

        public MainWindowViewModel(IRegionManager regionManager, 
                                 ICabinetInfoService cabinetInfoService, 
                                 IUserService userService, 
                                 IChatService chatService, 
                                 IPaymentService paymentService)
        {
            _regionManager = regionManager ?? throw new ArgumentNullException(nameof(regionManager));
            _cabinetInfoService = cabinetInfoService ?? throw new ArgumentNullException(nameof(cabinetInfoService));
            _userService = userService ?? throw new ArgumentNullException(nameof(userService));
            _chatService = chatService ?? throw new ArgumentNullException(nameof(chatService));
            _paymentService = paymentService ?? throw new ArgumentNullException(nameof(paymentService));

            // 初始化Modbus连接（暂时注释掉，避免网络连接问题）
            // OverAllContext.ModbusTcpLock = new ModbusTcpNet("192.168.1.102", 502);
            // OverAllContext.ModbusTcpStatusLight = new ModbusTcpNet("192.168.1.101", 502);
            // OverAllContext.ModbusTcpDoor = new ModbusTcpNet("192.168.1.100", 502);

            // 初始化命令
            NavigateToChatCommand = new DelegateCommand(NavigateToChat);
            NavigateToLoginCommand = new DelegateCommand(NavigateToLogin);
            NavigateToVipCommand = new DelegateCommand(NavigateToVip);
            LogoutCommand = new DelegateCommand(Logout);

            // 暂时注释掉后台任务，避免启动问题
            // RefreshLight();
            // RefreshIsTemperaturing();
        }

        private UserModel? _currentUser;
        public UserModel? CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        private bool _isLoggedIn = false;
        public bool IsLoggedIn
        {
            get => _isLoggedIn;
            set => SetProperty(ref _isLoggedIn, value);
        }

        public DelegateCommand NavigateToChatCommand { get; }
        public DelegateCommand NavigateToLoginCommand { get; }
        public DelegateCommand NavigateToVipCommand { get; }
        public DelegateCommand LogoutCommand { get; }

        /// <summary>
        /// 30s更新灯信号
        /// </summary>
        private void RefreshLight()
        {
            Task.Factory.StartNew(async () =>
            {
                // 柜子空的时候不亮灯，回温中红灯，回温结束绿灯
                // 遍历所有柜子的回温信息，如果回温完成写入灯的状态
                // 如果过保质期需要弹窗，回温结束也弹窗
                while (!cts.IsCancellationRequested)
                {
                    try
                    {
                        //TODO 优化方案： 根据历史柜子操作记录来更新灯信号
                        List<CabinetInfoModel> cabinetInfoModelList = _cabinetInfoService.FindAllCabinetInfos();
                        string output = string.Join("\n", cabinetInfoModelList);
    //                    File.AppendAllText("log.txt",
    //$"cabinetInfoModelList = {JsonSerializer.Serialize(cabinetInfoModelList, new JsonSerializerOptions { WriteIndented = true })}\n");
                        if (cabinetInfoModelList == null || cabinetInfoModelList.Count == 0)
                        {
                            await Task.Delay(30 * 1000);
                            continue;
                        }

                        foreach (var cabinetInfoModel in cabinetInfoModelList)
                        {
                            //TODO 如何熄灭灯
                            if (cabinetInfoModel.IsNull)
                            {
                                await OverAllContext.ModbusTcpLock.WriteAsync(cabinetInfoModel.GreenLightAddress.ToString(), false);
                            }
                            else
                            {
                                if (cabinetInfoModel.IsTemperaturing)
                                {
                                    await OverAllContext.ModbusTcpLock.WriteAsync(cabinetInfoModel.RedLightAddress.ToString(), true);
                                }
                                else
                                {
                                    await OverAllContext.ModbusTcpLock.WriteAsync(cabinetInfoModel.GreenLightAddress.ToString(), true);
                                }
                            }
                        }


                    }
                    catch (Exception ex)
                    {

                    }
                    await Task.Delay(30 * 1000);
                }


            }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }

        /// <summary>
        /// 30s刷新回温状态  
        /// </summary>
        private void RefreshIsTemperaturing()
        {
            Task.Factory.StartNew(async () =>
            {
                while (!cts.IsCancellationRequested)
                {
                    try
                    {
                        List<CabinetInfoModel> cabinetInfoModelList = _cabinetInfoService.FindAllCabinetInfos().Where(p => !p.IsNull).ToList();
                        if (cabinetInfoModelList == null || cabinetInfoModelList.Count == 0)
                        {
                            await Task.Delay(30 * 1000);
                            continue;
                        }

                        foreach (var cabinetInfoModel in cabinetInfoModelList)
                        {

                            if (cabinetInfoModel.IsTemperaturing && DateTime.Now >= cabinetInfoModel.TemperatureEndTime)
                            {
                                cabinetInfoModel.IsTemperaturing = false;
                            }
                        }

                        await _cabinetInfoService.EditCabinetInfoList(cabinetInfoModelList);
                    }
                    catch (Exception ex)
                    {

                    }

                    await Task.Delay(30 * 1000);
                }
            }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }

        /// <summary>
        /// 页面加载跳转登录界面
        /// </summary>
        public ICommand PageLoaded
        {
            get => new DelegateCommand(() =>
            {
                _regionManager.RequestNavigate("MainRegion", "LoginView");
            });
        }

        public ICommand ParaSettingCommand
        {
            get => new DelegateCommand(() =>
            {
                NavigationParameters keyValuePairs = new NavigationParameters();
               // keyValuePairs.Add("Menu", menuItem);
                _regionManager.Regions["MainRegion"].RequestNavigate("ParameterSettingView", keyValuePairs);
            });
        }

        public ICommand LoginCommand
        {
            get => new DelegateCommand(() =>
            {
                NavigationParameters keyValuePairs = new NavigationParameters();
                //keyValuePairs.Add("Menu", menuItem);
                _regionManager.Regions["MainRegion"].RequestNavigate("LoginRecordView", keyValuePairs);

            });
        }

        public ICommand ChambrierenCommand
        {
            get => new DelegateCommand(() =>
            {
                NavigationParameters keyValuePairs = new NavigationParameters();
                //keyValuePairs.Add("Menu", menuItem);
                _regionManager.Regions["MainRegion"].RequestNavigate("ChambrierenView", keyValuePairs);
            });
        }

        public ICommand OperateCommand
        {
            get => new DelegateCommand(() =>
            {
                NavigationParameters keyValuePairs = new NavigationParameters();
                //keyValuePairs.Add("Menu", menuItem);
                _regionManager.Regions["MainRegion"].RequestNavigate("OperateMachineView", keyValuePairs);
            });
        }

        public ICommand HistoryCommand
        {
            get => new DelegateCommand(() =>
            {
                NavigationParameters keyValuePairs = new NavigationParameters();
                //keyValuePairs.Add("Menu", menuItem);
                _regionManager.Regions["MainRegion"].RequestNavigate("HistoryRecordView", keyValuePairs);
            });
        }

        public ICommand AlarmCommand
        {
            get => new DelegateCommand(() =>
            {
                NavigationParameters keyValuePairs = new NavigationParameters();
                //keyValuePairs.Add("Menu", menuItem);
                //_regionManager.Regions["MainRegion"].RequestNavigate("AlarmRecordView", keyValuePairs);
                _regionManager.Regions["MainRegion"].RequestNavigate("CurrentCabinetView", keyValuePairs);

            });
        }

        private void NavigateToChat()
        {
            if (!IsLoggedIn)
            {
                MessageBox.Show("请先登录", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                NavigateToLogin();
                return;
            }

            var parameters = new NavigationParameters
            {
                { "CurrentUserId", CurrentUser!.UserId }
            };

            _regionManager.RequestNavigate("MainRegion", "ChatView", parameters);
        }

        private void NavigateToLogin()
        {
            _regionManager.RequestNavigate("MainRegion", "LoginView");
        }

        private void NavigateToVip()
        {
            if (!IsLoggedIn)
            {
                MessageBox.Show("请先登录", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                NavigateToLogin();
                return;
            }

            var parameters = new NavigationParameters
            {
                { "CurrentUserId", CurrentUser!.UserId }
            };

            _regionManager.RequestNavigate("MainRegion", "VipView", parameters);
        }

        private void Logout()
        {
            CurrentUser = null;
            IsLoggedIn = false;
            NavigateToLogin();
        }

        // 处理登录成功事件
        public void OnLoginSuccessful(UserModel user)
        {
            CurrentUser = user;
            IsLoggedIn = true;
            NavigateToChat();
        }
    }
}
